package com.wfm.mianshi.多个线程打印ABCABC;
import java.util.concurrent.Semaphore;

public class 利用Semaphore {
    static class PrintABCWithSemaphore {
        private static final int MAX_TIMES = 3;
        private final Semaphore semaphoreA = new Semaphore(1);
        private final Semaphore semaphoreB = new Semaphore(0);
        private final Semaphore semaphoreC = new Semaphore(0);

        public void printA() {
            try {
                for (int i = 0; i < MAX_TIMES; i++) {
                    semaphoreA.acquire();
                    System.out.print("A");
                    semaphoreB.release();
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }

        public void printB() {
            try {
                for (int i = 0; i < MAX_TIMES; i++) {
                    semaphoreB.acquire();
                    System.out.print("B");
                    semaphoreC.release();
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }

        public void printC() {
            try {
                for (int i = 0; i < MAX_TIMES; i++) {
                    semaphoreC.acquire();
                    System.out.print("C");
                    semaphoreA.release();
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }

    public static void main(String[] args) {
        PrintABCWithSemaphore printABC = new PrintABCWithSemaphore();

        Thread threadA = new Thread(printABC::printA);
        Thread threadB = new Thread(printABC::printB);
        Thread threadC = new Thread(printABC::printC);

        threadA.start();
        threadB.start();
        threadC.start();

        try {
            threadA.join();
            threadB.join();
            threadC.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
